//
//  NICustomLoading.m
//  ToyotaUccn
//
//  Created by 周晓旭 on 2021/3/17.
//  Copyright © 2021 CheYin. All rights reserved.
//

#import "NICustomLoading.h"

@interface NICustomLoading ()

@property (nonatomic, strong) UIView *loadingView;
@property (nonatomic, assign) BOOL isLoading;

@end

@implementation NICustomLoading

+ (instancetype)initInstance {
    static NICustomLoading *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[[self class] alloc] init];
    });
    return _instance;
}

- (UIView *)loadingView {
    if (!_loadingView) {
        _loadingView = [[UIView alloc] init];
        _loadingView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        _loadingView.layer.cornerRadius = 5;

        UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] init];
        [indicatorView startAnimating];
        indicatorView.color = [UIColor whiteColor];
        [_loadingView addSubview:indicatorView];
        [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loadingView).offset(30);
            make.centerX.equalTo(_loadingView);
        }];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.text = @"加载中...";
        [_loadingView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(indicatorView.mas_bottom).offset(10);
            make.left.equalTo(_loadingView).offset(20);
            make.right.equalTo(_loadingView).offset(-20);
            make.bottom.equalTo(_loadingView).offset(-20);
        }];

    }
    return _loadingView;
}

- (void)show {
    if (!self.isLoading) {
        self.isLoading = YES;
        self.frame = UIScreen.mainScreen.bounds;
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
        [self addSubview:self.loadingView];
        
        [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            make.width.mas_lessThanOrEqualTo(300);
            make.width.mas_greaterThanOrEqualTo(90);
        }];
    }
}

- (void)hide {
    self.isLoading = NO;
    [self removeFromSuperview];
}


@end
